<?php
// +----------------------------------------------------------------------
// | Author: wyd 2025/10/25
// | DESC: 
// +----------------------------------------------------------------------

declare (strict_types=1);


namespace My\core\frame;


use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;

class HttpServer
{
    private $server;
    private $dispatcher;

    public function __construct()
    {
        $this->server = new Server('0.0.0.0', 9501);

        $this->server->set([
            'worker_num' => 4,
            'daemonize' => false
        ]);

        $this->server->on('Request', [$this, 'request']);
        $this->server->on('Start', [$this, 'start']);
        $this->server->on('ShutDown', [$this, 'stop']);
        $this->server->on('WorkerStart', [$this, 'workerStart']);
    }

    //需要热更新的文件或代码应该放在此方法里加载
    public function workerStart(Server $server, $workerid)
    {
        cli_set_process_title('myswoole worker'); //设置进程名称

        \My\core\BeanFactory::init();
        $this->dispatcher = \My\core\BeanFactory::getBean(\My\core\frame\RouterCollector::class)->getDispatcher();
    }


    public function request(Request $request, Response $response)
    {
        $myRequest = \My\core\http\Request::init($request);
        $myResponse = \My\core\http\Response::init($response);

        if ($myRequest->uri() === '/favicon.ico') {
            $myResponse->status(404);
            $myResponse->end();
            return;
        }

        $routeInfo = $this->dispatcher->dispatch($myRequest->method(), $myRequest->uri());
        //var_dump($routeInfo);
        switch ($routeInfo[0]) {
            //$routeInfo,[]
            case \FastRoute\Dispatcher::NOT_FOUND:
                $myResponse->end();
                break;
            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                $myResponse->status(405);
                $myResponse->end();
                // ... 405 Method Not Allowed
                break;
            case \FastRoute\Dispatcher::FOUND:
                $handler = $routeInfo[1];       //是路由的处理程序，也就是在addRoute时传入的第三个参数（可以是闭包、函数名、类方法等）
                // $routeInfo[2];       是一个关联数组，包含路由中的命名参数（例如从路由模式中提取的）
                //例如，如果您的路由模式是'/user/{id}'，并且当前请求的URL是'/user/123'，那么$routeInfo[2]就是['id' => '123']。
                //$response->end($handler($routeInfo[2],[$myRequest]));  //第二个参数是扩展参数
                $myResponse->setBody($handler($routeInfo[2], [$myRequest]));
                $myResponse->end();
                break;
        }
    }

    public function start(Server $server)
    {
        cli_set_process_title('myswoole start'); //设置进程名称
        $mid = $server->master_pid;
        file_put_contents(__DIR__ . '/myswoole.pid', $mid);
    }

    public function run()
    {
        $p = new HotReload();
        //规定写法
        $this->server->addProcess($p->run());
        $this->server->start();
    }

    public function stop()
    {
        cli_set_process_title('myswoole stop'); //设置进程名称
        echo '服务关闭了' . PHP_EOL;
    }
}